package com.zakj.scservice.service;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;
import us.codecraft.webmagic.utils.HttpConstant;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * create by IntelliJ IDEA
 * Creator: HuangRZ
 * Email: huangrz11@163.com
 * Date: 2018/3/4
 * Description:
 **/
public class QunarOrderSearchProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000).setCharset("utf-8");

    private Pattern orderDetailUrlPattern = Pattern.compile("data-url=\"([A-Za-z0-9:/.?=$&;]*+)\"");

    @Override
    public void process(Page page) {

        Html html = page.getHtml();
        String title = html.xpath("/html/head/title/text()").toString();
        if ("我的订单 - 去哪儿网Qunar.com".equals(title)){
            List<String> orderDetailUrls = html.xpath("//a[@data-title='查看详情']").all();
            orderDetailUrls
                    .stream()
                    .map(s -> {
                        Matcher matcher = orderDetailUrlPattern.matcher(s);
                        matcher.find();
                        System.out.println(matcher.group(1));
                        return matcher.group(1);
                    })
                    .forEach(s -> {
                        Map<String, String> cookies = page.getRequest().getCookies();
                        Request request = new Request(s)
                                .setMethod("GET");
                        cookies.forEach(request::addCookie);
                        page.addTargetRequest(request);
                    });

        } else if ("订单详情".equals(title)){
            //乘机人的父节点
            String passenger_parent = "//div[@id='orderDetail-container']/div[@id='l-lside']/div[1]";
            //右边模块的父节点
            String right_parent = "//div[@id='orderDetail-container']/div[@id='l-rside']/div";

            Selectable PassengerSelectable = html.xpath(passenger_parent + "/div[@class'e-bd']");
            //开始解析乘机人
            List<String> names = html.xpath(passenger_parent + "/div[@class'e-bd']" + "/table/tbody/tr/td" + "/span[@class='name']/text()").all();
            names.forEach(System.out::println);

        }

    }

    @Override
    public Site getSite() {
        String str = "_i=HPDkUqcOnw6DYqTn-4xfex;_q=U.nbyftzz6825;_s=s_D6RNF44UXVUSZGN3QXKPSIWOZQ;_t=25449496;_v=SUbRgrB05wcixvvCK6lvvBSlyo5raF6sm6KrelO69FYEIbQp4P8cZjjRvRbuZYRfIUdLoV90w2IceLGXrIr3xINt0RNwXSm7gB7OJ1LqUYpMKUpFsOqSik8xX71pLL0uK5F3eKsD-VN6pF-VAOkfaMxc7lt_vsd3OJU4XwZ-VgEN;_vi=mSAemtG6Oqy0EtfII0wdkcvdfYfNkKQsD9VNMZIhsQLNrNThU0Ff5cH4_S51a0MC4sd6MB4qi_Psfnw2ZOaidN1YSupyBnHIsb5v0lXf3FR8VHSvZ25_xpk_yMoTfKth_dNOEtms-8MFyFbSS5gURYd7E5HDWi_p0WECwhnby43v;csrfToken=Kcld5f4gcxRbtLbEplxtb5bRp7mdf3qf;fid=32ef83f0-2073-462d-81a4-baf825ac9d66;QN1=O5cv5lqfguZ+gWvY2M4aAg==;QN163=0;QN205=organic;QN25=2472bb90-a42f-4995-b6dd-75a9cb9ce6f6-9f992f90;QN277=organic;QN268=|1520404546234_4b3f0264c7e52875;QN269=41642710C9AC11E7812DFA163E233FC1;QN271=60bd7954-a88c-49e0-9dea-99c31f945bc9;QN42=wpnh1770;QN44=nbyftzz6825;QN48=tc_188c0e198e70b124_161ff1a7623_b206;QN601=bacca0f6e4018c00150aa950251eef63;QN621=1490067914133=DEFAULT&fr=qunarindex;QN99=3964;trace=9fff42b35353405A;QunarGlobal=10.86.213.135_4b5b7b7a_161fed983eb_4c15|1520403378355;Hm_lpvt_75154a8409c0f82ecd97d538ff0ab3f3=1520405961;Hm_lvt_75154a8409c0f82ecd97d538ff0ab3f3=1520126892,1520134196,1520388853";
        Arrays.stream(str.split(";"))
                .forEach(s -> {
                    String[] split = s.split("=");
                    site.addCookie(split[0], split[1]);
                });
        return site;
    }

    @Test
    public void login(){
        System.getProperties().setProperty("webdriver.chrome.driver", "C:/Windows/System32/chromedriver.exe");
        RemoteWebDriver webDriver = new ChromeDriver();

        webDriver.get("https://user.qunar.com/passport/login.jsp");
        WebElement webElement = webDriver.findElement(By.xpath("//title"));
        System.out.println(webElement.getAttribute("outerHTML"));
        webDriver.close();

    }

    public static void main(String[] args){
        Spider.create(new QunarOrderSearchProcessor())
                .thread(5)
                .addPipeline(new ConsolePipeline())
                .addUrl("https://order.qunar.com/")
                .run();
    }

    @ToString
    private class model{

        @Getter@Setter private List<Passenger> passengers;
        @Getter@Setter private String date;
        @Getter@Setter private String flightInfo;
        @Getter@Setter private String depTime;
        @Getter@Setter private String arrTime;
        @Getter@Setter private String depAirport;
        @Getter@Setter private String arrAirport;
        @Getter@Setter private String farePrice;
    }

    @ToString
    private class Passenger {

        @Getter@Setter private String name;
        @Getter@Setter private String sex;
        @Getter@Setter private String nationality;
        @Getter@Setter private String number;
        @Getter@Setter private String status;

    }
}
